package nc.ui.arap.bx.listeners;

import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;
import java.util.Map;
import nc.bs.framework.common.NCLocator;
import nc.itf.fi.pub.Currency;
import nc.itf.uap.bd.psndoc.IPsnAccbankService;
import nc.itf.uap.bd.psndoc.IPsnDocQueryService;
import nc.ui.arap.bx.BXBillCardPanel;
import nc.ui.arap.bx.BXBillMainPanel;
import nc.ui.arap.bx.BxParam;
import nc.ui.arap.bx.VOCache;
import nc.ui.arap.bx.actions.BXDefaultAction;
import nc.ui.arap.bx.actions.ContrastAction;
import nc.ui.arap.bx.remote.PsnVoCall;
import nc.ui.arap.eventagent.EventTypeConst;
import nc.ui.bd.ref.AbstractRefGridTreeModel;
import nc.ui.bd.ref.AbstractRefModel;
import nc.ui.er.util.BXUiUtil;
import nc.ui.pub.ClientEnvironment;
import nc.ui.pub.beans.UIRefPane;
import nc.ui.pub.bill.BillCardPanel;
import nc.ui.pub.bill.BillData;
import nc.ui.pub.bill.BillEditEvent;
import nc.ui.pub.bill.BillItem;
import nc.ui.pub.bill.BillModel;
import nc.vo.arap.util.StringUtils;
import nc.vo.bd.CorpVO;
import nc.vo.bd.b06.PsndocVO;
import nc.vo.bd.psndoc.PsnAccbankUnionVO;
import nc.vo.bd.psndoc.PsnBasManUnionVO;
import nc.vo.bd.psndoc.PsnaccbankVO;
import nc.vo.ep.bx.BusiTypeVO;
import nc.vo.erm.util.ErVOUtils;
import nc.vo.erm.util.VOUtils;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;
import nc.vo.pub.ValidationException;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;
import nc.vo.sm.UserVO;

public class BxCardHeadEditListener extends BXDefaultAction
{
  public void afterEdit()
    throws BusinessException
  {
    EventObject event = (EventObject)getMainPanel().getAttribute(EventTypeConst.TEMPLATE_EDIT_EVENT);

    if ((event instanceof BillEditEvent))
    {
      BillEditEvent e = (BillEditEvent)event;
      String key = e.getKey();
      checkRuleAfterEdit(key);

      int pos = e.getPos();

      if (key.equals("fydwbm")) {
        initCostentityItems(true);
      }
      else if (key.equals("zfdwbm")) {
        initPayentityItems(true);
      }
      else if (key.equals("dwbm")) {
        initUseEntityItems(true);
      }
      else if (key.equals("jkbxr")) {
        String jkbxr = null;
        if (getBillCardPanel().getHeadItem(key).getValueObject() != null) {
          jkbxr = getBillCardPanel().getHeadItem(key).getValueObject().toString();
        }
        editPsninfo(jkbxr);
        changeFinItemValue("jkbxr", jkbxr);

        clearContrast();
      }
      else if (key.equals("receiver")) {
        editSkyhzh();
      } else if (key.equals("bzbm"))
      {
        String localCurrency = getBxParam().getLocalCurrPK();
        String bzbm = getBillCardPanel().getHeadItem("bzbm").getValueObject() == null ? null : getBillCardPanel().getHeadItem("bzbm").getValueObject().toString();

        if (bzbm == null) {
          return;
        }
        UFDouble[] cur = Currency.getRateBoth(this.pk_corp, bzbm, ClientEnvironment.getInstance().getDate().toString());
        if ((localCurrency != null) && (localCurrency.equals(bzbm)))
          getBillCardPanel().getHeadItem("bbhl").setEnabled(false);
        else {
          getBillCardPanel().getHeadItem("bbhl").setEnabled(true);
        }
        BXUiUtil.resetDecimal(getBillCardPanel(), null);
        getBillCardPanel().getHeadItem("bbhl").setValue(cur[1]);

        clearContrast();

        setHeadYFB();
        resetBodyFinYFB();
      } else if (key.equals("bbhl")) {
        setHeadYFB();
        resetBodyFinYFB();
      } else if (key.equals("ybje"))
      {
        setHeadYfbByHead();
        modify1FinRows("ybje");
      } else if (key.equals("amount")) {
        calculateFinitemAndHeadTotal();
        setHeadYFB();
      } else if (((key.equals("szxmid")) || (key.equals("szxmmc"))) && (pos == 1)) {
        if (!e.getTableCode().equals("er_finitem")) {
          calculateFinitemAndHeadTotal();
          setHeadYFB();
        }
      } else if (key.equals("total")) {
        setHeadYFB();
        modify1FinRows("total");
      } else if (key.equals("fkyhzh")) {
        getCardPanel().getHeadItem("mngaccid").setValue("");
        getCardPanel().getHeadItem("mngaccid_mc").setValue("");
      }
      else if (((key.equals("szxmid")) || (key.equals("jobid")) || (key.equals("cashproj"))) && (pos == 0)) {
        String value = "";
        try {
          Object valueObject = getBillCardPanel().getBillData().getHeadItem(key).getValueObject();
          value = valueObject == null ? null : valueObject.toString();
        } catch (NullPointerException ep) {
        }
        changeFinItemValue(key, value);
      }

      if ((ErVOUtils.getBusFinMap().containsKey(key)) && (pos == 1) && (!e.getTableCode().equals("er_finitem")) && (!e.getTableCode().equals("er_bxcontrast"))) {
        calculateFinitemAndHeadTotal();
      }

      if (getUserdefine(0, key, 2) != null) {
        String formula = getUserdefine(0, key, 2);
        String[] strings = formula.split(";");
        for (String form : strings) {
          doFormulaAction(form, key, -1, e.getTableCode(), e.getValue());
        }

      }

      doReimRuleAction();
    }
  }

  private void clearContrast() throws BusinessException, ValidationException
  {
    ContrastAction.doContrastToUI(getBxBillCardPanel(), getBillValueVO(), new ArrayList());

    getBxBillCardPanel().setContrast(false);
  }

  private void modify1FinRows(String headItem) {
    BillModel model = getBillCardPanel().getBillModel("er_finitem");
    if (model == null)
      return;
    int rowCount = model.getRowCount();

    if (rowCount == 1)
    {
      Object valueObject = getBillCardPanel().getHeadItem(headItem).getValueObject();
      UFDouble value = valueObject == null ? new UFDouble(0) : new UFDouble(valueObject.toString());
      model.setValueAt(value, 0, "ybje");
      modifyFinValues("ybje", 0);
    }

    getBxBillCardPanel().setFinchanged(true);
  }

  private void changeFinItemValue(String key, String value)
    throws ValidationException
  {
    BillCardPanel panel = getBillCardPanel();
    String[] tableCodes = getBillCardPanel().getBillData().getBodyTableCodes();
    for (String tableCode : tableCodes) {
      BillItem[] items = panel.getBillModel(tableCode).getBodyItems();
      for (BillItem item : items) {
        if (key.equals(item.getKey())) {
          int rowCount = panel.getBillModel(tableCode).getRowCount();
          for (int i = 0; i < rowCount; i++) {
            panel.getBillModel(tableCode).setValueAt(value, i, key);
          }
        }
      }
      panel.getBillModel(tableCode).execLoadFormula();
    }
    getBxBillCardPanel().setFinchanged(true);
  }
  private void editPsninfo(String jkbxr) throws BusinessException {
    String deptid = "";
    if ((jkbxr != null) && (!jkbxr.equals(""))) {
      IPsnDocQueryService pd = (IPsnDocQueryService)NCLocator.getInstance().lookup(IPsnDocQueryService.class.getName());
      PsnBasManUnionVO[] pm = pd.queryPsnUnionVosByManDocCondition(" pk_psndoc='" + jkbxr + "'");
      if (pm.length != 0) {
        PsndocVO psnmanvo = pm[0].getPsnmanvo();
        deptid = psnmanvo.getPk_deptdoc();
      }
    }
    getBillCardPanel().setHeadItem("deptid", deptid);
    Object dwbm = getBillCardPanel().getHeadItem("dwbm").getValueObject();
    Object fydwbm = getBillCardPanel().getHeadItem("fydwbm").getValueObject();
    if ((dwbm != null) && (fydwbm != null) && (dwbm.equals(fydwbm)) && (getBillCardPanel().getHeadItem("fydeptid").isEdit())) {
      getBillCardPanel().setHeadItem("fydeptid", deptid);
    }

    editSkyhzh();
  }

  public void editSkyhzh() throws BusinessException {
    editSkyhzh(true);
  }

  public void editSkyhzh(boolean autotake) throws BusinessException {
    BillItem headItem = getBillCardPanel().getHeadItem("receiver");

    String jkbxr = (String)getBillCardPanel().getHeadItem("jkbxr").getValueObject();
    String receiver = headItem == null ? null : (String)headItem.getValueObject();
    String jkbxr_basdoc = "";

    if (!StringUtils.isNullWithTrim(receiver)) {
      jkbxr = receiver;
    }

    if (jkbxr == null) {
      return;
    }
    if (ClientEnvironment.getInstance().getValue(PsnVoCall.PSN_PK_ + getBxParam().getPk_user() + getBxParam().getPk_corp()) != null) {
      if (jkbxr.equals(ClientEnvironment.getInstance().getValue(PsnVoCall.PSN_PK_ + getBxParam().getPk_user() + getBxParam().getPk_corp())))
        jkbxr_basdoc = (String)ClientEnvironment.getInstance().getValue(PsnVoCall.PSNBAS_PK_ + getBxParam().getPk_user() + getBxParam().getPk_corp());
      else
        jkbxr_basdoc = getBxrpk(jkbxr, jkbxr_basdoc);
    }
    else {
      jkbxr_basdoc = getBxrpk(jkbxr, jkbxr_basdoc);
    }
    UIRefPane ref = (UIRefPane)getCardPanel().getHeadItem("skyhzh").getComponent();
    ref.setWhereString(" bd_PsnAccbank.pk_psnbasdoc='" + jkbxr_basdoc + "'");
    IPsnAccbankService pa = (IPsnAccbankService)NCLocator.getInstance().lookup(IPsnAccbankService.class.getName());
    PsnAccbankUnionVO[] pavos = null;

    if (autotake)
      try {
        pavos = (PsnAccbankUnionVO[])(PsnAccbankUnionVO[])pa.queryByPsnaccbankByPsnAndCondition(jkbxr_basdoc, "bd_PsnAccbank.isreimburse='Y' and bd_PsnAccbank.pk_psnbasdoc='" + jkbxr_basdoc + "'");
        if ((pavos != null) && (pavos.length != 0))
          getBillCardPanel().setHeadItem("skyhzh", pavos[0].getPsnaccbankVO().getPk_accbank());
        else
          getBillCardPanel().setHeadItem("skyhzh", null);
      }
      catch (Exception e)
      {
        getBillCardPanel().setHeadItem("skyhzh", "");
      }
  }

  private String getBxrpk(String jkbxr, String jkbxr_basdoc)
    throws BusinessException
  {
    String pk_corp = (String)getBillCardPanel().getHeadItem("dwbm").getValueObject();
    IPsnDocQueryService pd = (IPsnDocQueryService)NCLocator.getInstance().lookup(IPsnDocQueryService.class.getName());
    String where = " pk_psndoc='" + jkbxr + "'";
    if (pk_corp == null) {
      where = where + " and pk_corp='" + pk_corp + "'";
    }
    PsnBasManUnionVO[] pm = pd.queryPsnUnionVosByManDocCondition(where);
    if (pm.length != 0) {
      PsndocVO psnmanvo = pm[0].getPsnmanvo();
      jkbxr_basdoc = psnmanvo.getPk_psnbasdoc();
    }
    return jkbxr_basdoc;
  }

  public void initPayentityItems(boolean isEdit)
  {
    BusiTypeVO busTypeVO = getBusTypeVO();
    List payentity_billitems = busTypeVO.getPayentity_billitems();
    if(!busTypeVO.getId().equals("264X-8")){
    	initItemsBelong(payentity_billitems, "zfdwbm", null, isEdit);
    }
  }
  public void initUseEntityItems(boolean isEdit) throws BusinessException {
    BusiTypeVO busTypeVO = getBusTypeVO();
    List payentity_billitems = busTypeVO.getUseentity_billitems();
    initItemsBelong(payentity_billitems, "dwbm", null, isEdit);
  }
  public void initCostentityItems(boolean isEdit) {
    BusiTypeVO busTypeVO = getBusTypeVO();
    List costentity_billitems = busTypeVO.getCostentity_billitems();
    if(!busTypeVO.getId().equals("264X-8")){
    	initItemsBelong(costentity_billitems, "fydwbm", null, isEdit);
    }
  }

  public void initAllItemsToCurrPk() {
    BillItem[] headItems = getBillCardPanel().getHeadShowItems();
    initAllitemsToCurrcorp(headItems);
    String[] tables = getBillCardPanel().getBillData().getBodyTableCodes();
    for (String tab : tables) {
      BillItem[] bodyItems = getCardPanel().getBillData().getBodyShowItems(tab);
      if (bodyItems == null)
        continue;
      initAllitemsToCurrcorp(bodyItems);
    }
  }

  private void initAllitemsToCurrcorp(BillItem[] headItems) {
    for (BillItem headItem : headItems) {
      String refType = headItem.getRefType();
      if ((refType == null) || (refType.equals("")) || (headItem.getComponent() == null) || (!(headItem.getComponent() instanceof UIRefPane))) continue;
      try {
        UIRefPane ref = (UIRefPane)headItem.getComponent();
        String pk_corp2 = ClientEnvironment.getInstance().getCorporation().getPk_corp();
        if (!ref.getPk_corp().equals(pk_corp2)) {
          ref.setPk_corp(pk_corp2);
          ref.setValue(null);
        }
      }
      catch (ClassCastException e)
      {
      }
    }
  }

  public void initPowerItems()
  {
    BillItem[] headItems = getCardPanel().getHeadShowItems();
    List<String> power_items = getBusTypeVO().getPower_items();
    Map<String, String> mapItems = (Map<String, String>)VOUtils.changeCollectionToMap(power_items);
    String[] tables = getBillCardPanel().getBillData().getBodyTableCodes();
    for (String tab : tables) {
      BillItem[] bodyItems = getCardPanel().getBillData().getBodyShowItems(tab);
      if (bodyItems == null)
        continue;
      initAllItemsPower(bodyItems, mapItems);
    }

    initAllItemsPower(headItems, mapItems);
  }

  private void initAllItemsPower(BillItem[] headItems, Map<String, String> mapItems) {
    for (BillItem headItem : headItems) {
      String refType = headItem.getRefType();
      if ((refType == null) || (refType.equals("")) || (headItem.getComponent() == null) || (!(headItem.getComponent() instanceof UIRefPane)) || (
        (!mapItems.containsKey(headItem.getKey())) && ((headItem.getIDColName() == null) || (!mapItems.containsKey(headItem.getIDColName()))))) continue;
      try {
        UIRefPane ref = (UIRefPane)headItem.getComponent();

        AbstractRefModel refModel = ref.getRefModel();

        if (refModel != null)
        {
          if (!(refModel instanceof AbstractRefGridTreeModel));
        }
      }
      catch (ClassCastException e)
      {
      }
    }
  }

  public void initItemsBelong(List<String> costentity_billitems, String key, Object fydwbm, boolean isEdit)
  {
    if (fydwbm == null)
      fydwbm = getHeadValue(key);
    if ((fydwbm == null) || (fydwbm.equals("")))
      return;
    String fyPkCorp = fydwbm.toString();
    for (String item : costentity_billitems) {
      if (item.equals(key)) {
        continue;
      }
      BillItem[] headItems = getItemsById(item);
      if (headItems == null)
        continue;
      for (BillItem headItem : headItems) {
        if (headItem == null)
          continue;
        String refType = headItem.getRefType();
        if ((refType != null) && (!refType.equals("")) && (headItem.getComponent() != null) && ((headItem.getComponent() instanceof UIRefPane))) {
          try {
            UIRefPane ref = (UIRefPane)headItem.getComponent();
            ref.setPk_corp(fyPkCorp);
            if (ref.getRefModel() != null) {
              ref.getRefModel().setFilterPks(new String[0], 1);
            }

            if (isEdit)
              if (headItem.getPos() == 0) {
                headItem.setValue(null);
              } else if (headItem.getPos() == 1) {
                String tableCode = headItem.getTableCode();
                int rowCount = getBillCardPanel().getBillModel(tableCode).getRowCount();
                for (int i = 0; i < rowCount; i++) {
                  getBillCardPanel().setBodyValueAt(null, i, headItem.getKey(), tableCode);
                  getBillCardPanel().setBodyValueAt(null, i, headItem.getIDColName(), tableCode);
                }
              }
          }
          catch (ClassCastException e)
          {
          }
        }
        if ((!item.equals("jkbxr")) || (getBxParam().getIsQc())) continue;
        try {
          initSqdlr(getMainPanel(), headItem, getVoCache().getCurrentDjlxbm(), getCardPanel().getHeadItem("dwbm"));
        }
        catch (Exception e)
        {
        }
      }
    }
  }

  protected BillItem[] getItemsById(String item) {
    if ((item.equals("szxmid")) || (item.equals("jobid")) || (item.equals("jkbxr")) || (item.equals("cashproj"))) {
      String[] tables = getBillCardPanel().getBillData().getBodyTableCodes();
      List results = new ArrayList();

      if (getCardPanel().getHeadItem(item) != null) {
        results.add(getCardPanel().getHeadItem(item));
      }

      for (String tab : tables) {
        BillItem[] bodyItems = getCardPanel().getBillData().getBodyItemsForTable(tab);
        if (bodyItems == null)
          continue;
        for (BillItem key : bodyItems) {
          if ((key.getIDColName() != null) && (key.getIDColName().equals(item))) {
            results.add(key);
          }
        }
      }

      return (BillItem[])results.toArray(new BillItem[0]);
    }
    return new BillItem[] { getCardPanel().getHeadItem(item) };
  }

  public static void initSqdlr(BXBillMainPanel panel, BillItem headItem, String billtype, BillItem headCorp) throws BusinessException
  {
    if (headItem == null)
      return;
    String refType = headItem.getRefType();

    if (refType == null)
      return;
    String corp = "";
    if ((headCorp != null) && (headCorp.getValueObject() != null)) {
      corp = headCorp.getValueObject().toString();
    }
    if ((corp == null) || (corp.trim().length() == 0)) {
      corp = ClientEnvironment.getInstance().getCorporation().getPk_corp();
    }
    String wherePart = BXUiUtil.getAgentWhereString(billtype, ClientEnvironment.getInstance().getUser().getPrimaryKey(), ClientEnvironment.getInstance().getDate().toString(), corp);

    if ((refType != null) && (!refType.equals("")))
      try {
        UIRefPane ref = (UIRefPane)headItem.getComponent();
        String whereStr = ref.getRefModel().getWherePart();
        if (!whereStr.contains("select pk_user from er_sqdlr")) {
          whereStr = whereStr + wherePart;
        }
        ref.setWhereString(whereStr);
      }
      catch (ClassCastException e)
      {
      }
  }
}